package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.pojos.ApUser;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 搜索
     *
     * @param dto
     * @return
     * @throws IOException
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (null == dto || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolquery = QueryBuilders.boolQuery();
        //多条件查询所以用布尔
        //关键词查询
        boolquery.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR));
         //--------
        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null && dto.getFromIndex() == 0) {
            //异步保存，用户搜索记录
            apUserSearchService.insert(dto.getSearchWords(), user.getId());}
            //-------
            if (null != dto.getMinBehotTime()) {
                boolquery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

            }
            searchSourceBuilder.query(boolquery);
            //分页
            searchSourceBuilder.from(dto.getFromIndex());
            searchSourceBuilder.size(dto.getPageSize());
            //按照时间倒序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);
            //处理高亮
            HighlightBuilder highilghtBuilder = new HighlightBuilder();
            highilghtBuilder.field("title");
            highilghtBuilder.preTags("<font style='color: red; font-size: inherit;'>");
            highilghtBuilder.postTags("</font>");
            searchSourceBuilder.highlighter(highilghtBuilder);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //处理结果
            SearchHit[] hits = searchResponse.getHits().getHits();
            List<Map> list = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                //处理内容数据
                String jsonString = hit.getSourceAsString();
                Map map = JSON.parseObject(jsonString, Map.class);
                //处理高亮数据
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (null != highlightFields && highlightFields.size() > 0) {
                    HighlightField highlightField = highlightFields.get("title");
                    Text[] texts = highlightField.getFragments();
                    String h_title = StringUtils.join(texts);
                    map.put("h_title", h_title);
                } else {
                    map.put("h_title", map.get("title"));
                }
                list.add(map);
            }
            return ResponseResult.okResult(list);
        }
    }
